"""
客户跟进提醒功能
"""
from datetime import datetime, timedelta
from flask import current_app
from app import db
from app.models.customer import FollowUp
from app.models.user import User, Notification
from app.utils.email import send_email


def send_followup_reminders():
    """
    发送跟进提醒
    包括：
    1. 即将到期的跟进提醒（未来7天内）
    2. 已过期的跟进提醒
    3. 解决方案配合提醒
    """
    try:
        # 1. 处理即将到期的跟进提醒
        upcoming_followups = FollowUp.get_upcoming_followups(days=7)
        for followup in upcoming_followups:
            send_upcoming_followup_reminder(followup)
            # 标记提醒已发送
            followup.reminder_sent = True
            followup.reminder_time = datetime.now()
        
        # 2. 处理已过期的跟进提醒
        overdue_followups = FollowUp.get_overdue_followups()
        for followup in overdue_followups:
            send_overdue_followup_reminder(followup)
            # 标记提醒已发送
            followup.reminder_sent = True
            followup.reminder_time = datetime.now()
        
        # 3. 处理解决方案配合提醒
        pending_followups = FollowUp.get_solution_support_pending()
        for followup in pending_followups:
            # 检查是否需要发送提醒（例如，创建24小时后仍未确认）
            if need_solution_support_reminder(followup):
                send_solution_support_reminder(followup)
        
        # 提交所有更改
        db.session.commit()
        return True, "提醒发送成功"
    except Exception as e:
        current_app.logger.error(f"发送跟进提醒失败: {str(e)}")
        db.session.rollback()
        return False, f"发送跟进提醒失败: {str(e)}"


def send_upcoming_followup_reminder(followup):
    """
    发送即将到期的跟进提醒
    """
    # 计算剩余天数
    days_remaining = (followup.next_followup_time - datetime.now()).days
    if days_remaining < 0:
        days_remaining = 0
    
    # 创建系统通知
    notification = Notification(
        user_id=followup.manager_id,
        title=f"跟进提醒: {followup.customer.name}",
        content=f"您有关于客户「{followup.customer.name}」的跟进计划将在{days_remaining}天后到期，跟进时间：{followup.next_followup_time.strftime('%Y-%m-%d %H:%M')}",
        notification_type="跟进提醒"
    )
    db.session.add(notification)
    
    # 发送邮件提醒（如果用户配置了邮件）
    manager = User.query.get(followup.manager_id)
    if manager and manager.email:
        try:
            subject = f"跟进提醒: {followup.customer.name}"
            html_content = f"""
            <p>尊敬的{manager.username}，</p>
            <p>您有关于客户「{followup.customer.name}」的跟进计划将在{days_remaining}天后到期，请及时处理：</p>
            <ul>
                <li>客户名称：{followup.customer.name}</li>
                <li>跟进时间：{followup.next_followup_time.strftime('%Y-%m-%d %H:%M')}</li>
                <li>跟进方式：{followup.method}</li>
                <li>跟进内容：{followup.content[:100]}{'...' if len(followup.content) > 100 else ''}</li>
            </ul>
            <p>请登录系统查看详情并完成跟进。</p>
            <p>此邮件由系统自动发送，请勿回复。</p>
            """
            send_email(subject, [manager.email], html_content)
        except Exception as e:
            current_app.logger.error(f"发送跟进提醒邮件失败: {str(e)}")


def send_overdue_followup_reminder(followup):
    """
    发送已过期的跟进提醒
    """
    # 计算过期天数
    days_overdue = (datetime.now() - followup.next_followup_time).days
    
    # 创建系统通知
    notification = Notification(
        user_id=followup.manager_id,
        title=f"跟进逾期提醒: {followup.customer.name}",
        content=f"您关于客户「{followup.customer.name}」的跟进计划已逾期{days_overdue}天，原计划时间：{followup.next_followup_time.strftime('%Y-%m-%d %H:%M')}",
        notification_type="跟进逾期提醒"
    )
    db.session.add(notification)
    
    # 发送邮件提醒（如果用户配置了邮件）
    manager = User.query.get(followup.manager_id)
    if manager and manager.email:
        try:
            subject = f"跟进逾期提醒: {followup.customer.name}"
            html_content = f"""
            <p>尊敬的{manager.username}，</p>
            <p>您关于客户「{followup.customer.name}」的跟进计划已逾期{days_overdue}天，请尽快处理：</p>
            <ul>
                <li>客户名称：{followup.customer.name}</li>
                <li>原计划时间：{followup.next_followup_time.strftime('%Y-%m-%d %H:%M')}</li>
                <li>逾期天数：{days_overdue}天</li>
                <li>跟进方式：{followup.method}</li>
                <li>跟进内容：{followup.content[:100]}{'...' if len(followup.content) > 100 else ''}</li>
            </ul>
            <p>请登录系统查看详情并尽快完成跟进。</p>
            <p>此邮件由系统自动发送，请勿回复。</p>
            """
            send_email(subject, [manager.email], html_content)
        except Exception as e:
            current_app.logger.error(f"发送跟进逾期提醒邮件失败: {str(e)}")
    
    # 如果是销售人员，同时通知其上级经理
    if manager and manager.role == 'sales' and manager.manager_id:
        manager_notification = Notification(
            user_id=manager.manager_id,
            title=f"下属跟进逾期提醒: {followup.customer.name}",
            content=f"您的下属「{manager.username}」关于客户「{followup.customer.name}」的跟进计划已逾期{days_overdue}天",
            notification_type="下属跟进逾期提醒"
        )
        db.session.add(manager_notification)


def send_solution_support_reminder(followup):
    """
    发送解决方案配合提醒
    """
    if not followup.solution_support_user_id:
        return
    
    # 创建系统通知给解决方案人员
    notification = Notification(
        user_id=followup.solution_support_user_id,
        title=f"解决方案配合请求: {followup.customer.name}",
        content=f"销售人员「{followup.manager.username}」请求您配合处理客户「{followup.customer.name}」的跟进，请及时确认配合",
        notification_type="解决方案配合提醒"
    )
    db.session.add(notification)
    
    # 发送邮件提醒（如果用户配置了邮件）
    solution_user = User.query.get(followup.solution_support_user_id)
    if solution_user and solution_user.email:
        try:
            subject = f"解决方案配合请求: {followup.customer.name}"
            html_content = f"""
            <p>尊敬的{solution_user.username}，</p>
            <p>销售人员「{followup.manager.username}」请求您配合处理客户「{followup.customer.name}」的跟进：</p>
            <ul>
                <li>客户名称：{followup.customer.name}</li>
                <li>销售人员：{followup.manager.username}</li>
                <li>跟进时间：{followup.followup_time.strftime('%Y-%m-%d %H:%M')}</li>
                <li>跟进方式：{followup.method}</li>
                <li>跟进内容：{followup.content[:100]}{'...' if len(followup.content) > 100 else ''}</li>
            </ul>
            <p>请登录系统查看详情并确认配合。</p>
            <p>此邮件由系统自动发送，请勿回复。</p>
            """
            send_email(subject, [solution_user.email], html_content)
        except Exception as e:
            current_app.logger.error(f"发送解决方案配合提醒邮件失败: {str(e)}")


def need_solution_support_reminder(followup):
    """
    判断是否需要发送解决方案配合提醒
    规则：创建24小时后仍未确认的记录
    """
    # 检查是否已确认
    if followup.solution_confirmed:
        return False
    
    # 检查是否已发送过提醒
    if followup.reminder_sent:
        return False
    
    # 检查是否已过24小时
    time_diff = datetime.now() - followup.created_at
    if time_diff.total_seconds() < 24 * 3600:  # 24小时
        return False
    
    return True


def reset_reminder_status(followup_id):
    """
    重置跟进记录的提醒状态
    当跟进时间被修改时调用此函数
    """
    followup = FollowUp.query.get(followup_id)
    if followup:
        followup.reminder_sent = False
        followup.reminder_time = None
        db.session.commit()
        return True
    return False